var Utils = Utils || {};
var url = window.location.href.split("/sop");
var _serverUrl=url[0]+'/restfull/';

Utils.isCode = false;//是否调用微信接口 true本地
Utils.isDebug=false;//是否开启本地测试 true:本地   注意！！！！部署到服务环境时，一定要设置为false!!!!
Utils.appid='wx24a55113f76b8638'; // 测试用appID为wx24a55113f76b8638，生产用appID为wxa628463b4a757e15
var sessionId=getSession(); //会话ID
var openid=''; //open ID
var customerId=''; //客户ID
var mobileNum=''; //电话号码
/**
 * 封装请求参数
 * @param reqJson
 * @return
 */
function reorganizeParams(reqJson){
    var header = new Object();
    if(this.sessionId != null){
        header.sessionId = this.sessionId;
    }else{
        header.sessionId = "";
    }

    var reqData = new Object();
    if(reqJson != null){
        reqData.body = reqJson;
    }else{
        reqData.body = "";
    }
    reqData.header = header;

    return jQstringifyes(reqData);
}

/**
 * rem实现页面自适应
 * */
Utils.adaptive = function() {
    ! function() {
        function e() {
            var e = document.documentElement.clientWidth,
                t = document.querySelector("html"),
                f = (e > 750 ? 750 : e) / 20;
            window.fontSize = f;
            t.style.fontSize = f + "px"
        }

        e(), window.addEventListener("resize", e);
    }();
};
Utils.adaptive();

/**
 * 设置json 字符串格式
 * @param obj 对象
 * @return json 字符串格式
 */
function jQstringifyes(obj){
    var arr = [];
    $.each( obj, function( key, val ) {
        var next ='"'+ key + '":';
        next += $.isPlainObject( val ) ? printObj(val):'"'+val+'"';
        arr.push( next );
    });
    return "{ " + arr.join( "," ) + " }";
};

function printObj(val){
    return JSON.stringify(val)
}

/**
 * 调农行接口ajax方法
 * @param url {string} 请求地址
 * @param jsonDsata {object} 请求参数
 * @param ajaxCallbackObj {object} 回调函数
 */
Utils.doAjaxInterface=function(url,jsonDsata,ajaxCallbackObj){
    var serverUrl=_serverUrl+url;//请求地址

    var reqData = reorganizeParams(jsonDsata);
    $.ajax({
        url: serverUrl,
        type: "post",
        async: true,
        data: {
            'reqJson': reqData
        },
        dataType:"json",
        success: function(data) {
            if(!data) {
                alert("数据异常，请稍后再试！")
                return;
            }
            ajaxCallbackObj.doSuccess(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            ajaxCallbackObj.doError();
            //alert(errorThrown);
        }
    });
}

/**
 * 构建load加载
 * */
var loadModule = {
    show: function() {
        $(".mask-wrap").show();
        $(".loadingimg").show();
        $(".mask-background").show();
    },
    showLoad: function() {
        $(".mask-wrap").show();
        $(".loadingimg").show();
    },
    hide: function() {
        $(".mask-wrap").hide();
        $(".mask-background").hide();
        $(".loadingimg").hide();
    }
};

/**
 * 构建系统弹窗框
 * */
var errorAlert = {
    time: 3000,
    create: function() {
        if($(".errorAlert-wrap").length > 0) {
            return this;
        }
        var html = '<div class="errorAlert-wrap" id="errorAlert">' +
            '<div class="errorAlert">' +
            '<div class="errorAlert-backgroud"></div>' +
            '<div class="errorAlert-text"></div>' +
            '</div>' +
            '</div>';
        $("body").append(html);
    },
    show: function(retMsg, time) {
        if($(".errorAlert-wrap").length == 0) {
            this.create();
        }
        var time = time || this.time;
        var bol = this;
        $(".errorAlert-wrap").show();
        $(".errorAlert-text").html(retMsg);
        $("#errorAlert").click(function() {
            bol.hide();
        });
        this.timer = setTimeout(function() {
            $(".errorAlert-wrap").hide();
        }, time);
    },
    hide: function() {
        $(".errorAlert-wrap").hide();
        $(".errorAlert-text").html("");
        clearInterval(this.timer);
    }
};

/**
 * 获取url链接上的参数
 * */
Utils.getQueryString = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if(r != null) return r[2];
    return "";
};

/**
 * 设置cookie元素
 * @param cname
 * @param cvalue
 * @param delay
 * @param timeUnit 时间单元（millisecond,second,minute,hour,day（默认））
 * @return
 */
function setCookie(cname, cvalue, delay, timeUnit) {
    var pathName=window.document.location.pathname;
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);

    var delayTimes;
    if(timeUnit == undefined){
        delayTimes = Number(delay*24*60*60*1000);
    }else if(timeUnit == "hour"){
        delayTimes = Number(delay*60*60*1000);
    }else if(timeUnit == "minute"){
        delayTimes = Number(delay*60*1000);
    }else if(timeUnit == "second"){
        delayTimes = Number(delay*1000);
    }else if(timeUnit == "millisecond"){
        delayTimes = Number(delay);
    }

    var d = new Date();
    d.setTime(d.getTime() + delayTimes);
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires+";path="+projectName;
}

/**
 * 获取cookie元素
 * @param cname
 * @return
 */
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

/**
 * 删除cookie元素
 * @param name
 * @return
 */
function delCookie(name) {
    setCookie(name, "", -1);
}

/**
 * 更新cookie
 * @return
 */
function initSession(){
    sessionId=getSession();
    setCookie("sessionId", sessionId, 30, "minute");
}

/**
 * 添加会话ID
 * @return
 */
function addSession(){
    setCookie("sessionId", sessionId, 30, "minute");
}

/**
 * 获取session
 */
function getSession(){
    return getCookie("sessionId");
}

/**
 * 获取cookie元素
 * @param cname
 * @return
 */
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1)
        {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
